// import styles from './popup.css'
let styles = require('./popup.css').default

interface Ipopup {
  width?: string;
  height?: string;
  title?: string;
  pos?: 'center'|'left-top'|'left-bottom'|'right-top'|'right-bottom'|'left'|'right'|'top'|'bottom';
  mask?: boolean;
  content?: (content: HTMLElement|Element) => void;
}

interface Icomponent {
  tempContainer: HTMLElement;
  init: () => void;
  template: () => void;
  handle: () => void;
}

export default function popup (options?: Ipopup) {
  return new Popup(options)
}

class Popup implements Icomponent {
  tempContainer: HTMLElement;
  mask: HTMLElement;
  constructor (private settings: Ipopup) {
    this.settings = {
      width: '100%',
      height: '100%',
      title: '',
      pos: 'center',
      mask: true,
      content: function (){},
      ...this.settings,
    }
    this.init();
  }
  init () {
    this.template();
    this.settings.mask && this.createMask()
    this.handle();
    this.contentCallback();
  }
  template () {
    this.tempContainer = document.createElement('div')
    this.tempContainer.style.width = this.settings.width
    this.tempContainer.style.height = this.settings.height
    this.tempContainer.classList.add(styles.popup)
    this.tempContainer.innerHTML = `
      <div class="${styles['popup-title']}">
        <h3>${this.settings.title}</h3>
        <i class="icon-close"></i>
      </div>
      <div class="${styles['popup-content']}"></div>
    `
    document.body.appendChild(this.tempContainer)
    console.log(window.innerHeight, window.innerWidth, this.tempContainer.offsetHeight, this.tempContainer.offsetWidth)
    switch(this.settings.pos) {
      case 'left':
        this.tempContainer.style.left = '0px'
        this.tempContainer.style.top = (window.innerHeight - this.tempContainer.offsetHeight)/2 + 'px'
        break;
      case 'right':
        this.tempContainer.style.right = '0px'
        this.tempContainer.style.top = (window.innerHeight - this.tempContainer.offsetHeight)/2 + 'px'
        break;
      default:
        this.tempContainer.style.left = (window.innerWidth - this.tempContainer.offsetWidth)/2 + 'px'
        this.tempContainer.style.top = (window.innerHeight - this.tempContainer.offsetHeight)/2 + 'px'
        break;
    }
  }
  handle () {
    const popupClose = this.tempContainer.querySelector(`.${styles['popup-title']} i`)
    console.log(popupClose)
    popupClose.addEventListener('click', () => {
      document.body.removeChild(this.tempContainer)
      this.settings.mask && document.body.removeChild(this.mask)
    })
  }
  createMask () {
    this.mask = document.createElement('div');
    this.mask.classList.add(styles.mask);
    this.mask.style.width = '100%'
    this.mask.style.height = document.body.offsetHeight + 'px';
    document.body.appendChild(this.mask);
  }
  contentCallback () {
    const popupContent = this.tempContainer.querySelector(`.${styles['popup-content']}`)
    this.settings.content(popupContent)
  }
}